package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kaixin.connect.Kaixin;
import com.kaixin.connect.KaixinJavaScriptInterface;
import com.kaixin.connect.NotifyKaixinVerify;
import com.mime.qweibo.JavaScriptInterface;
import com.mime.qweibo.MyWebViewClient;
import com.mime.qweibo.NotifyQWeiboVerify;
import com.renren.api.connect.android.TestConnectButtonListener;
import com.renren.api.connect.android.view.ConnectButton;
import com.renren.api.connect.android.view.RenrenEventListener;
import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.UserInfo;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.appshare.threads.LoginKaixinThread;
import com.secneo.appshare.threads.LoginQWeiboThread;
import com.secneo.appshare.threads.QWeiboGetAccessToken;
import com.secneo.mp.api.database.DatabaseHelper;
import com.secneo.mp.api.util.MpUtil;

public class LoginChooseMethodActivity extends Activity 
				implements OnClickListener, RenrenEventListener, NotifyQWeiboVerify
{
	private Button mLoginFBBtn;
	private Button mLoginRegularBtn,btn_register;
	private CheckBox mLegalCheckBox;
	private TextView mLegalTextView;
    private TextView LostPasswordTextView;
	private EditText loginAccountEditText,loginPasswordEditText;
	private Button mLoginQWeibo;
	private Button mLoginKaixin;
	private WebView mWebView ;	//for qweibo
	private WebView mKaixinWebView ;	//for kaixin
	private ProgressDialog mNetProgressBar = null;
	private ConnectButton login;

	 public Handler mHandler1 = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				switch (msg.what)
				{
					case 1:
						if (mNetProgressBar != null) 
						{
							mNetProgressBar.dismiss();
							mNetProgressBar = null; 
						}
						ActivityUtil.alert(LoginChooseMethodActivity.this,
								"无此安卓号");
						break;
					case 2:
						if (mNetProgressBar != null) 
						{
							mNetProgressBar.dismiss();
							mNetProgressBar = null; 
						}
						ActivityUtil.alert(LoginChooseMethodActivity.this,
								"密码错误");
							break;
					case 3:
						if (mNetProgressBar != null) 
						{
							mNetProgressBar.dismiss();
							mNetProgressBar = null; 
						}
						ActivityUtil.alert(LoginChooseMethodActivity.this,
								"登录失败，未知错误");	
							break;
					case 4:
						if (mNetProgressBar != null) 
						{
							mNetProgressBar.dismiss();
							mNetProgressBar = null; 
						}
						ActivityUtil.alert(LoginChooseMethodActivity.this,
						"网络异常，请检查网络连接");	
							break;
					case 10:
						if (mNetProgressBar != null) 
						{
							mNetProgressBar.dismiss();
							mNetProgressBar = null; 
						}
						    Intent intent = new Intent();
		  					intent.setClass(LoginChooseMethodActivity.this, MainActivity.class);
		  					intent.putExtra("weiboLogin", false);
		  					startActivity(intent);
		  					finish();
							break;
							
					default:
						if (mNetProgressBar != null) {
							mNetProgressBar.dismiss();
							mNetProgressBar = null; 
						}
						break ;
					
				}
				super.handleMessage(msg);
			}
		};

	//for qweibo
	private String request_token = new String() ;
	private String request_token_secret = new String() ;
	private String verify = new String() ;

	public Handler mHandler = new Handler(){


		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:		//腾讯微博得到授权的request token
				
				if (mNetProgressBar != null) 
				{
					mNetProgressBar.dismiss();
					mNetProgressBar = null; 
				}
				mWebView = (WebView)findViewById(R.id.qweibocWebView);
				mWebView.setVisibility(View.VISIBLE) ;
				//根据id找到相应的WebView
				
				//加载设置
				WebSettings webSetting = mWebView.getSettings();
				//支持ajax
				webSetting.setJavaScriptEnabled(true);
				//支持中文ou
				webSetting.setDefaultTextEncodingName("utf-8");
				//设置允许访问文件数据
				webSetting.setAllowFileAccess(true);
				//设置支持缩放
				webSetting.setBuiltInZoomControls(true);
				//使用WebChromClient功能
				mWebView.setWebChromeClient(new WebChromeClient());
				
				MyWebViewClient webViewClient = new MyWebViewClient() ;
				
				mWebView.setWebViewClient(webViewClient) ;
				
				mWebView.addJavascriptInterface(
						new JavaScriptInterface(LoginChooseMethodActivity.this), 
						"Methods") ;
				
				Bundle bundle = msg.getData() ;
				request_token = bundle.getString(Constants.QWEIBO_TOKEN_ACTION) ;
				request_token_secret = bundle.getString(Constants.QWEIBO_TOKEN_SECRET_ACTION) ;
				
				//加载uri  
				mWebView.loadUrl(
						"http://open.t.qq.com/cgi-bin/authorize?oauth_token="
						+ request_token);
				break ;
			case 2:		//得到access token	
				Log.d("qq" , "get access_token") ;
				if (mNetProgressBar != null) 
				{
					mNetProgressBar.dismiss();
					mNetProgressBar = null; 
				}
				LocalStore.getLocaleStoreInstance().setTencentAccountActive() ;
				Intent intent = new Intent();
				
				if(msg.getData().getBoolean("first_login")){
					Bundle mBundle = new Bundle(); 
					mBundle.putInt("sns_type", Constants.SNS_INDEX_TENCENT);
					intent.putExtras(mBundle);
					intent.setClass(LoginChooseMethodActivity.this, UserInfoActivity.class);
				} else {
					Bundle mBundle = new Bundle(); 
					mBundle.putInt("sns_type", Constants.SNS_INDEX_TENCENT);
					intent.putExtras(mBundle);
					intent.setClass(LoginChooseMethodActivity.this, ChooseUserActivity.class);
				}
				
				Bitmap bmp = BitmapFactory.decodeResource(LoginChooseMethodActivity.this.getResources(), R.drawable.icon);
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
	            byte[] content = baos.toByteArray();

				if(!Constants.SWITCH_SINA_CUSTOM){
					RemoteApiImpl rai = new RemoteApiImpl() ;
					rai.share2QWeiboMsg(LoginChooseMethodActivity.this, 
							Constants.UPLOAD_ACTION_LOGIN, null, 
							content, null, null, null) ;
				}
				bmp.recycle();bmp = null;
				startActivity(intent);
				finish();
				break ;
			case 3:		//登录腾讯微博失败
				Toast.makeText(LoginChooseMethodActivity.this, 
						R.string.label_fb_login_failed, Toast.LENGTH_LONG).show() ;
				mWebView.setVisibility(View.GONE) ;
				if (mNetProgressBar != null) 
				{
					mNetProgressBar.dismiss();
					mNetProgressBar = null; 
				}
				break ;
			case 4:
				mWebView.setVisibility(View.GONE) ;
				break ;
			case 5:		//sns账号已经绑定过其他账号，需要提示登出
				if(mWebView != null)
					mWebView.setVisibility(View.GONE) ;
				if (mNetProgressBar != null) 
				{
					mNetProgressBar.dismiss();
					mNetProgressBar = null; 
				}
				String nickName = msg.getData().getString("nickName") ;
				String tmp = "安卓号 "+nickName + " 已被绑定过，只能销毁原账号才能进行绑定操作。详见帮助。" ;
				ActivityUtil.alert(LoginChooseMethodActivity.this, tmp) ;
			case 50:
	    		Intent intentw = new Intent();
	    		if(msg.getData().getBoolean("first_login")){
					Bundle mBundle = new Bundle(); 
					mBundle.putInt("sns_type", Constants.SNS_INDEX_RENREN);
					intentw.putExtras(mBundle);
	    			intentw.setClass(LoginChooseMethodActivity.this, UserInfoActivity.class);
					startActivity(intentw);
	    		} else {
					Bundle mBundle = new Bundle(); 
					mBundle.putInt("sns_type", Constants.SNS_INDEX_RENREN);
					intentw.putExtras(mBundle);
	    			intentw.setClass(LoginChooseMethodActivity.this, ChooseUserActivity.class);
					startActivity(intentw);
	    		}
				
				finish();
				break ;
				

			case 201:		//开心网得到授权的request token
				
				if (mNetProgressBar != null) 
				{
					mNetProgressBar.dismiss();
					mNetProgressBar = null; 
				}
				mKaixinWebView = (WebView)findViewById(R.id.kaixinWebView);
				mKaixinWebView.setVisibility(View.VISIBLE) ;
				//根据id找到相应的WebView
				
				//加载设置
				WebSettings webKaixinSetting = mKaixinWebView.getSettings();
				//支持ajax
				webKaixinSetting.setJavaScriptEnabled(true);
				//支持中文ou
				webKaixinSetting.setDefaultTextEncodingName("utf-8");
				//设置允许访问文件数据
				webKaixinSetting.setAllowFileAccess(true);
				//设置支持缩放
				webKaixinSetting.setBuiltInZoomControls(true);
				//使用WebChromClient功能
				
				//加载uri  
				Kaixin kaixin = Kaixin.getInstance();
				String url = Kaixin.KX_AUTHORIZE_URL 
					+ "?oauth_token=" + kaixin.getRequestToken()
					+ "&oauth_client=1";
				mKaixinWebView.loadUrl(url);
				
				LocalStore.getLocaleStoreInstance().setStoredActivity(
						LoginChooseMethodActivity.this);
				
				break ;
				
			default:
				break ;
			}
		}
	} ;

    public void onEventLogined(String event){
    	
    	if(LocalStore.getLocaleStoreInstance(this).accountIsActive(3)){
    		return;
    	}
    	
    	if( event.compareTo("renrenlogin")==0 ){
    		
    		LocalStore.getLocaleStoreInstance(this).setRenrenAccountActive();
    		    		
    		Thread loadThread = new Thread()
    		{		
    			public void run()
    			{
    				try
    				{
    					LocalStore.getLocaleStoreInstance().getRenrenUserInfo();
    		    		LocalStore.getLocaleStoreInstance().setRenrenAccountActive();
    					
    					RemoteApiImpl remoteApi = new RemoteApiImpl();
    					UserInfo ret = null;
    					String localName = LocalStore.getLocaleStoreInstance().getNickName();
    					String localIcon = LocalStore.getLocaleStoreInstance().getAvatarName();
    					
    					boolean first_login = (LocalStore.getLocaleStoreInstance().getAndroidId() == null ||
    							LocalStore.getLocaleStoreInstance().getAndroidId() == "") ? true : false ;

    					
    					if(localName.equals("")){
    						localName = LocalStore.getLocaleStoreInstance().getRenrenUserNameString();
    						localIcon = LocalStore.getLocaleStoreInstance().getRenrenPicUrlString();
    					}
    					
						ret = remoteApi.addNewWeiboUser(LoginChooseMethodActivity.this, 4, 
								LocalStore.getLocaleStoreInstance().getRenrenUidString(), 
								localName, localIcon);
    					
						if (ret == null) 
							Log.d("MyTag", "Register renren user failed!");
						else
						{
							if(ret.id.equals(Constants.SNS_HAS_ASSOCIATE) || 
									ret.id == Constants.SNS_HAS_ASSOCIATE){
								Message msg = new Message() ;
								Bundle data = new Bundle() ;
			    				msg.what = 5 ;
			    				data.putString("nickName", LocalStore.getLocaleStoreInstance().getRenrenUserNameString()) ;
			    				msg.setData(data) ;
			    				mHandler.sendMessage(msg) ;
			    				return ;
			    			}
							
							Log.d("MyTag", "Register renren user success!");
							if(ret.id != null && !"".equals(ret.id)){
								LocalStore.getLocaleStoreInstance().setUid(ret.id);
								LocalStore.getLocaleStoreInstance().setAndroidId(ret.androidId);
							}
	    					LocalStore.getLocaleStoreInstance().storeRenrenAccountInfoToLocal();

							LocalStore.getLocaleStoreInstance().setNickName(ret.nick);
							LocalStore.getLocaleStoreInstance().setAvatarName(localIcon);
						}
    					
				    	Message msg = new Message() ;
				    	Bundle data = new Bundle() ;
				    	data.putBoolean("first_login", first_login) ;
				    	msg.setData(data) ;
				    	msg.what = 50 ;
				    	mHandler.sendMessage(msg);
				    	
						Bitmap bmp = BitmapFactory.decodeResource(LoginChooseMethodActivity.this.getResources(), R.drawable.icon);
			            ByteArrayOutputStream baos = new ByteArrayOutputStream();
			            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
			            byte[] content = baos.toByteArray();
						ActivityUtil.shareToWeibo(LoginChooseMethodActivity.this, Constants.UPLOAD_ACTION_LOGIN, null, null, content, null, 
								Constants.SERVER_BANGSHARE_ICON_URL, null, null);
						bmp.recycle();bmp = null;
						
    				} catch (Exception ex)
    				{
    					LocalStore.getLocaleStoreInstance().logoutRenrenAccount();
    					ex.printStackTrace();
    				}
    			}
    		};
    		loadThread.start();
    		
    	}
    }


    public void onEventLogouted(String event){
    	
    	if( event.compareTo("renrenlogout")==0 ){
//        	getUserId();
    	}
    }
    
    public boolean onRenrenEventClicked(){
		if (!mLegalCheckBox.isChecked())
		{
			Animation localAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_draw_attention);
			mLegalCheckBox.startAnimation(localAnimation);
			return false;
		}
    	return true;
    }
    

    //for qweibo get verify 得到access token
    public void SetVerify(String verify){
    	
    	Log.d("qq" , "get verify" + verify) ;
    	
    	String prompt = getResources().getString(R.string.login_ing) ;
    	
		mNetProgressBar = ProgressDialog.show(this, null,prompt ,true);
    	
    	this.verify = verify ; 
    	QWeiboGetAccessToken thread = new QWeiboGetAccessToken(
    			this, mHandler, request_token, request_token_secret, verify) ;
    	thread.start() ;
    	/*Message msg = new Message() ;
    	msg.what = 3 ;
    	mHandler.sendMessage(msg) ;    	*/
    }
    
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_login);
		AppShareApplication.getInstance().addActivity(this);
        this.login = (ConnectButton) findViewById(R.id.btn_login_renren);
        this.login.init(Constants.RENREN_BUTTON_LOGIN_CHOICE, LocalStore.getLocaleStoreInstance(this).getRenren(), this, this);
        this.login.setConnectButtonListener(new TestConnectButtonListener());
		if(Constants.SWITCH_SINA_CUSTOM){
			this.login.setVisibility(View.GONE);
		}
        

		mLoginFBBtn = (Button) findViewById(R.id.btn_login_weibo);
		mLoginFBBtn.setOnClickListener(this);
		
		mLoginRegularBtn = (Button) findViewById(R.id.btn_login_regular);
		mLoginRegularBtn.setOnClickListener(this);

		loginAccountEditText=(EditText)findViewById(R.id.LoginAccountEditText);
		
		loginPasswordEditText=(EditText)findViewById(R.id.LoginPasswordEditText);
		btn_register= (Button) findViewById(R.id.btn_register);
		btn_register.setOnClickListener(this);

		mLoginQWeibo = (Button) findViewById(R.id.btn_login_qweibo) ;
		mLoginQWeibo.setOnClickListener(this) ;
		if(Constants.SWITCH_SINA_CUSTOM){
			mLoginQWeibo.setVisibility(View.GONE);
		}
		
		mLoginKaixin = (Button) findViewById(R.id.btn_login_kaixin);
		mLoginKaixin.setOnClickListener(this);
		if(Constants.SWITCH_SINA_CUSTOM){
			mLoginKaixin.setVisibility(View.GONE);
		}
		


		mLegalCheckBox = (CheckBox) findViewById(R.id.chk_legal_terms);
		String privacy = getString(R.string.label_privacy_policy);
		String termOfService = getString(R.string.label_terms_of_service);
		String legalformat = getString(R.string.label_legal);
		String legal = String.format(legalformat, termOfService, privacy);

		mLegalCheckBox.setText(legal);
		mLegalCheckBox.setChecked(true);
		mLegalTextView = (TextView) findViewById(R.id.label_legal_terms_links);
		
		String legal2format = getString(R.string.label_legal_link);
		mLegalTextView.setText(Html.fromHtml("<u>"+legal2format+"</u>"));
		mLegalTextView.setTextColor(Color.BLACK);
		mLegalTextView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				HelpWebViewActivity.go(LoginChooseMethodActivity.this, Constants.TERM_OF_SERVICE_URL, "");	
			}
		});
		LostPasswordTextView = (TextView) findViewById(R.id.LostPasswordTextView);
		
		String legal2format1 ="忘记密码";
		LostPasswordTextView.setText(Html.fromHtml("<u>"+legal2format1+"</u>"));
		LostPasswordTextView.setTextColor(Color.BLACK);
		LostPasswordTextView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				DatabaseHelper dh1 = new DatabaseHelper(LoginChooseMethodActivity.this);
				dh1.insertUserAppPopularityBycatagory(LoginChooseMethodActivity.this, 2000);
				dh1.close();
			Intent	intentw = new Intent();
				intentw.setClass(LoginChooseMethodActivity.this, MemberSettingLostPasswordActivity.class);
				startActivity(intentw);
				finish();
			}
		});
		
	}
	
	
	@Override
	public void onClick(View v)
	{
		if (!mLegalCheckBox.isChecked())
		{
			Animation localAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_draw_attention);
			mLegalCheckBox.startAnimation(localAnimation);
			return;
		}
		
		Intent intentw;
		switch (v.getId())
		{
			case R.id.btn_login_weibo:
		    	 MpUtil.setMobileVersion(String.valueOf(Constants.VERSION_CODE));
				MpUtil.setPackageName(Constants.PACKAGENAME);
				
				 
				intentw = new Intent();
				Bundle bundle=new Bundle();
				bundle.putInt(Constants.EXIT_BEHAVIOUR,Constants.EXIT_BEHAVIOUR_GOTO_MAIN);
				intentw.putExtras(bundle);
				intentw.setClass(this, LoginWeiboMethodActivity.class);
				startActivity(intentw);
				finish();
				return;
/*	
			case R.id.btn_login_renren:
				 
			*/	
			case R.id.btn_login_regular:
				
				if (ActivityUtil.isEmpty(loginAccountEditText,loginPasswordEditText)) {
					ActivityUtil.alert(LoginChooseMethodActivity.this, "安卓号和密码不能为空");
					return;
				} else {
					if(!Util.isLegalAndroidAccount(loginAccountEditText.getText().toString().trim()))
					{
						String str = getResources().getString(R.string.txt_prompt_anddr_account_fmt_error) ;
						ActivityUtil.alert(LoginChooseMethodActivity.this, str);
						return;
					}
					mNetProgressBar = ProgressDialog.show(this, null,
							 "正在登录中..." ,true);
					Thread dengluThread = new Thread() 
			           {
			              public void run() 
			              {
			            		RemoteApiImpl rai = new RemoteApiImpl();
			            	  UserInfo ret = rai.loginUser(LoginChooseMethodActivity.this,Integer.valueOf(loginAccountEditText.getText().toString().trim()),loginPasswordEditText.getText().toString().trim());
			            	 if(ret!=null)
			            	 {
			            	  if (!"".equals(ret.id) && ret.id != null) {
			            		  LocalStore.getLocaleStoreInstance(
			            				  LoginChooseMethodActivity.this).setBangAccountActive();
			            		  LocalStore.getLocaleStoreInstance(
			            				  LoginChooseMethodActivity.this).setAndroidId(
			            						  loginAccountEditText.getText().toString().trim());
			            		  LocalStore.getLocaleStoreInstance(
			            				  LoginChooseMethodActivity.this).setNickName(
													ret.nick);
									LocalStore.getLocaleStoreInstance(
											LoginChooseMethodActivity.this).setUid(
											ret.id);
									LocalStore.getLocaleStoreInstance(LoginChooseMethodActivity.this).setAvatarName(ret.avatar);
			            		 
			  					Message msg = new Message();
					   			   msg.what =10;
					   			mHandler1.sendMessage(msg);
			  					return;
								} else {
									if ("badname".equals(ret.error)) {
										Message msg = new Message();
							   			   msg.what =1;
							   			mHandler1.sendMessage(msg);
										return;
										
									} 
									else if("badpassword".equals(ret.error)) {
										Message msg = new Message();
							   			   msg.what =2;
							   			mHandler1.sendMessage(msg);
										return;
									}else{
										Message msg = new Message();
							   			   msg.what =3;
							   			mHandler1.sendMessage(msg);
										return;
									}
								}
			            	 }else
			            	 {
			            		 Message msg = new Message();
					   			   msg.what =4;
					   			mHandler1.sendMessage(msg); 
			            	 }
			              }
					};
					dengluThread.start();
				}
				return;
				
				
			case R.id.btn_register:
				DatabaseHelper dh=new DatabaseHelper(LoginChooseMethodActivity.this);
				dh.insertUserAppPopularityBycatagory(LoginChooseMethodActivity.this,2053);
				dh.close();
				
				Intent intent1 = new Intent();
				intent1.setClass(LoginChooseMethodActivity.this, RegisterActivity.class);
				startActivity(intent1);
				finish();							
				return;
				
			case R.id.btn_login_qweibo:
				
				Log.d("qq" , "btn_login_qweibo") ;
				String prompt = getResources().getString(R.string.login_qweibo_ing) ;
				mNetProgressBar = ProgressDialog.show(this, null,prompt ,true);
				
				LoginQWeiboThread thread = new LoginQWeiboThread(this, mHandler) ;
				thread.start() ;
				return;
				
			case R.id.btn_login_kaixin:
				
				Log.d("MyTag" , "btn_login_kaixin");
				LoginKaixinThread kaixinThread = new LoginKaixinThread(this, mHandler);
				kaixinThread.start();
				/*
				Intent intent = new Intent();
				intent.setClass(LoginChooseMethodActivity.this, KaixinLoginFinishActivity.class);
				startActivity(intent);
				*/
				return;
				
		}
	}
	

	/* 退出处理 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (View.VISIBLE==mKaixinWebView.getVisibility())
			{
				mKaixinWebView.setVisibility(View.GONE);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
